<template>
  <div class="editProject">
  <a-spin :spinning="spinning">
    <div class="projectConetnt">
      <div class="createTitle">{{ $route.name }}</div>
      <properComp
        class="createProper"
        :isShow="isShow"
        :fromData="fromData"
        :requireObj="requireObj"
        :inputValue="inputValue"
        :isEditPage="true"
        :smallTypeIsDisplay="smallTypeIsDisplay"
        @raidoChange="raidoChange"
        @showModal="showModal"
        :beforeSubmit="beforeSubmit"
        :projectTypeData="projectTypeData"
      ></properComp>
      <common-modal
        :modalVisible="modalVisible"
        @handleOk="handleOk"
        @handCancel="handCancel"
        :selectType="'radio'"
        :itemArr="itemArr"
      ></common-modal>
      <a-drawer
      title="关联的规划项目"
      :width="'800px'"
      :visible="drawerVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <div class="seerchBox" style="float: right; margin-bottom: 10px;z-index: 999;position: relative;">
        <global-search ref="globalSearch" :searchTableData="searchData1" @onSearch="onSearch1"></global-search>
      </div>
      <common-table
        :columns="columns1"
        :tableData="tableData1"
        :isRowsSelectVisible="isRowsSelectVisible"
        :selectType="selectType"
        :data-row-key="'oid'"
         @selectedRows="selectedRowsProject"
      ></common-table>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="onClose">
          确定
        </a-button>
      </div>
    </a-drawer>
    <a-drawer
      title="关联的规划书"
      :width="'800px'"
      :visible="drawerProjectVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onCloseProject"
    >
      <div class="seerchBox" style="float: right; margin-bottom: 10px;z-index: 999;position: relative;">
        <global-search ref="globalSearch" :searchTableData="searchData" @onSearch="onSearch"></global-search>
      </div>
      <common-table
        :columns="columns2"
        :tableData="tableData"
        :isRowsSelectVisible="isRowsSelectVisible"
        :selectType="selectType"
        :data-row-key="'oid'"
        @selectedRows="selectedRowsBook"
      ></common-table>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onCloseProject">
          取消
        </a-button>
        <a-button type="primary" @click="onCloseProject">
          确定
        </a-button>
      </div>
    </a-drawer>
    </div>
    <div class="footer">
      <div class="cancel" @click="cancelProject">取消</div>
      <div class="confirm" @click="submitProject">确定</div>
    </div>
    </a-spin>
  </div>
</template>
<script>
import properComp from "@/components/propertyCommon";
import commonModal from "@/components/common/commonModal.vue";
import { editProject, getRelatedPlanning, getProjectType,
        getRelatedProject, getManagerMiddle, serveManager, saveProject, searchUserIdMiddle, getProductCategoryByGroup} from "@api/singleProject"
import commonTable from "@/components/common/commonTable";
import {columnsProject, columnsPlanning} from "@/utils/constant/constant.js";
import { Message } from "ant-design-vue";
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
import _ from 'lodash'
// import fromObj from "@/components/propertyCommon/data";
import globalSearch from "@/components/common/globalSearch"
export default {
  name: "createProject",
  components: {
    properComp,
    commonModal,
    commonTable,
    globalSearch
  },
  data() {
    return {
      spinning: false,
      projectTypeData: [], // 编辑项目项目大类
      fromData: [], //表单渲染
      requireObj: {}, // 表单提交验证
      isShow: false,
      // fromObj: {},
      modalId: "",
      modalVisible: false, // 弹框显示隐藏
      drawerVisible: false,
      drawerProjectVisible: false, // 关联的规划项目
      tableData: [], // 关联规划书数据
      searchData: [],
      searchData1: [],
      tableData1: [], // 关联规划项目数据
      isRowsSelectVisible: true,
      selectType: "radio",
      columns1: columnsProject,
      columns2: columnsPlanning,
      userId: userinfo.loginName,
      selectBook: "",
      itemArr: [],
      inputValue: {},
      projectId: sessionStorage.getItem("oid"), // 项目id
      isSubmit: false,
      checkedItem: [], //需要校验的值
      checked: true,
      beforeSubmit: false,
      smallTypeIsDisplay: "",//小类类型
    };
  },
  mounted() {
    this.getCreateProject()
    this.getProjectTypeData()
  },
  watch: {
    $route: {
      handler(n) {
        this.getCreateProject()
      },
      deep: true,
      immediate: true,
    },
    //所属组织
    "requireObj.projectGroupReference": {
      handler(v) {
        let groupName = ""
        this.requireObj.ProductCategory = ""
        this.fromData.forEach(function(items) {
          items.rows.forEach(function(itms) {
            itms.items.forEach(function(itm) {
              if(itm.id == 'projectGroupReference') {
                for(let key in itm.selects) {
                  if(itm.selects[key] == v) {
                    groupName = key.split("-")[0]
                    return
                  }
                }
              }
            }) 
          })
        })
        getProductCategoryByGroup({groupName}).then(res1 => {
          // if()
          if(res1.status === 200 && res1.data.success) {
            let data = res1.data.data
            let arrs = {}
            data.forEach(item => {
              let obj = {}
              obj[item] = item
              arrs = Object.assign({},arrs,obj)
            })
            this.fromData.forEach(function(item1) {
              item1.rows.forEach(function(itm1) {
                itm1.items.forEach(function(itms1) {
                  if(itms1.id == 'ProductCategory') {
                    itms1.selects = arrs
                  }
                }) 
              })
            })
          } else {
            this.$message.error(res1.data.message || "请求失败")
          }
        })
      }
    }
  },
  // beforeRouteEnter(to,from,next) {
  //   to.meta.keepAlive = false
  //   next()
  // },
  methods: {
    //将工艺类切换小类时隐藏的字段置空
    removeHiddenFields(arr) {
      for (let key in this.requireObj) {
        if(arr.indexOf(key) != -1) {
          this.requireObj[key] = ""
        } 
      }
    },
    // 1.获取项目类型数据
    getProjectTypeData() {
      let params = {
        objType: "com.pisx.pmgt.project.PIProject",
        userId:  this.userId,
      }
      getProjectType(params).then(res=>{
        if(res.status === 200){
          let projectTypeZh = sessionStorage.getItem('projecttype')
          this.projectTypeData = res.data.data.filter(v => v.displayName === projectTypeZh)
          console.log(this.projectTypeData,13);
        }else{
          this.projectTypeData =[]
        }
      })
    },
    /* 全局搜索 */
    onSearch(tableVal, searchValue) {
      if (!searchValue) {
        this.tableData = this.searchData
      } else {
        this.tableData = tableVal
      }
    },
    /* 全局搜索 */
    onSearch1(tableVal, searchValue) {
      if (!searchValue) {
        this.tableData1 = this.searchData1
      } else {
        this.tableData1 = tableVal
      }
    },
    // 获取创建项目表单
    getCreateProject() {
      let params = {
        oid: `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem("oid")}`
      }
      editProject(params).then(res=>{
        if(res.status === 200){
          if(res.data.success){
            if(res.data.data){
              let arr = {}
              res.data.data[0].rows.forEach(item=>{
                item.items.forEach(i=>{
                  arr[i.id] = i.value
                })
              })
              this.getFromData(res.data.data);
            }
          }else{
            Message.error('请求失败')
          } 
        }else{
          Message.error('请求失败')
        }
      })
    },
    // 2.获取表单渲染数据
    getFromData(res) {
      let requiredArr = ["RequirementsSource","TechnologySpecialty","ImportantGrade","ProjectBonus","isEquipmentModification","IslightPlant"]
      // setTimeout(() => {
        let data = res;
        data.forEach(item => {
          item.rows.forEach(ele => {
            ele.items.forEach(i => {
              // 1. 将select数据对象转化为数组
              this.$set(i, "selectArr", []);
              if (i.selects && i.selects !== null) {
                let obj = i.selects;
                for (let key in obj) {
                  i.selectArr.push(obj[key]);
                }
              }
              if(sessionStorage.getItem("projecttype") === "制造工艺提升项目" && requiredArr.indexOf(i.id) != -1) {
                i.required = true;
              }
              // 2. 处理特殊情况
              switch (i.id) {
                case "calendarReference":
                  i.formType = "select";
                  break;
                case "projectTemplateReference":
                  i.formType = "select";
                  break;
                case "projectGroupReference":
                  i.formType = "select";
                  break;
                case "PlanningYear":
                  i.formType = "select";
                  break;
                case "ReleatedPlanningBook":
                  i.formType = "modal";
                  break;
                case "ReleatedPlanningProject":
                  i.formType = "modal";
                  break;
                case "ProjectMananger":
                  i.formType = "modal";
                  break;
                default:
                  break;
              }
              // 3.将id提取出来组成校验对象集
              this.$set(this.requireObj, i.id, i.valueInner ? i.valueInner :  i.value);
              // this.requireObj.ProjectMananger = i.valueInner
              // if(i.id === "ProjectMananger"){
              //   if(i.value && i.valueInner == null){
              //     delete this.requireObj.ProjectMananger
              //   }
              // }
              this.$set(this.inputValue, i.id, i.value)
            });
          });
        });
        console.log(data, 246);
        this.fromData = data;
        this.checkProject()
        //   // 4. 判断特殊显示隐藏
        this.getSpecialVisible(this.fromData);
      // }, 1000);
    },
    // 判断特殊显示隐藏
    getSpecialVisible(data) {
      data.forEach(item => {
        item.rows.forEach(ele => {
          ele.items.forEach(i => {
            if (this.requireObj["isPlanningProject"] === "是") {
              if (
                i.id === "PlanningYear" ||
                i.id === "ReleatedPlanningBook" ||
                i.id === "ReleatedPlanningProject"
              ) {
                i.required = true;
                this.$set(i, "specialVisible", false);
              }
            } else {
              if (
                i.id === "PlanningYear" ||
                i.id === "ReleatedPlanningBook" ||
                i.id === "ReleatedPlanningProject"
              ) {
                i.required = false;
                this.$set(i, "specialVisible", true);
              }
            }
          });
        });
      });
    },
    // 单选
    raidoChange(val) {
      this.getSpecialVisible(this.fromData);
    },
    // 弹窗显示
    showModal(val) {
      /**这里需要取当前点击input的id，来匹配requireObj里面的key值，在handeOk里面赋值 */
      for (let key in this.requireObj) {
        if (key === val.id) {
          this.modalId = key;
        }
      }
      for (let key in this.inputValue) {
        if (key === val.id) {
          this.modalId = key;
        }
      }
      if (val.id === "ProjectMananger") {
        this.modalVisible = true;
        this.getManager()
      } else if (val.id === "ReleatedPlanningBook") {
        this.relatedPlanning()
      } else if (val.id === "ReleatedPlanningProject") {
        this.relatedProject()
      }
    },
    // 项目经理
    getManager() {
      getManagerMiddle().then(res=>{
        if(res.data.staffList){
          const arr = res.data.staffList.split(',')
          const newStaffList = arr.filter((item,index) => {
            return arr.indexOf(item,0) ===index
          }) 
          let newArr = []
          let newList = []
          if(newStaffList.length > 10){
            newList = newStaffList.slice(-10)
          }else{
            newList = newStaffList
          }
          let params = {
            match: true,
            userIds: newList,
          }
          searchUserIdMiddle(params).then(res1=>{
            res1.data.map(item=>{
              item.checked = false
            })
            newArr.push(res1.data) 
            this.itemArr = newArr.flat()
          })
        }
      })
    },
    // 数组对象去重
    unique(arr) {
      const res = new Map()
      return arr.filter((arr1) => !res.has(arr1.userNo) && res.set(arr1.userNo, 1))
    },
    // 关联规划书
    relatedPlanning() {
      if(!this.requireObj.projectGroupReference){
        Message.error("请先选择所属组织")
        return 
      }
      if(!this.requireObj.PlanningYear){
        Message.error("请先选择规划年份")
        return 
      }
      this.drawerProjectVisible = true
      const params = {
        userId: this.userId,
        oid: this.requireObj.projectGroupReference,
        plannYear: this.requireObj.PlanningYear,
     }
     getRelatedPlanning(params).then(res=>{
       if(res.status === 200){
         if(res.data.success && res.data.data){
            this.tableData = res.data.data
            this.searchData = res.data.data//按照创建时间降序排序
         }else{
           this.searchData = []
         Message.error("数据查询失败")
        }
       }else{
         Message.error("数据查询失败")
       }
     })
      
    },
    // 关联规划项目
    relatedProject() {
      if(!this.selectBook){
        Message.error("请先选择关联项目规划书")
        return 
      }
       this.drawerVisible = true;
      const params = {
        userId: this.userId,
        oid: this.selectBook,
     }
     getRelatedProject(params).then(res=>{
       if(res.status === 200){
         if(res.data.success){
           if(res.data.data){
             this.tableData1 = res.data.data
             this.searchData1 = res.data.data//按照创建时间降序排序
           }
         }else{
           this.searchData1 = []
           Message.error("数据查询失败")
         }
         
       }else{
          Message.error("数据查询失败")
       }
     })
    },
    // 添加项目经理
    handleOk(val) {
      console.log(val, '400');
      this.inputValue[this.modalId] = val.name
      this.requireObj[this.modalId] = val.userId;
      let params = {
        staffList: val.userId,
        userId: this.userId
      }
      serveManager(params).then(res=>{
        if(res.result){
          Message.success('添加成功')
        }
      })
      this.modalVisible = false;
    },
    handCancel() {
      this.modalVisible = false;
    },
    // 关闭抽屉(规划项目)
    onClose() {
      this.drawerVisible = false;
    },
    // 关闭抽屉(规划书)
    onCloseProject() {
      this.drawerProjectVisible = false;
    },
    // 单选
    selectedRowsBook(val) {
      this.selectBook = val[0].oid
      this.inputValue.ReleatedPlanningBook = val[0].name
      this.requireObj.ReleatedPlanningBook = val[0].oid
    },
    selectedRowsProject(val){
      this.inputValue.ReleatedPlanningProject = val[0].name
      this.requireObj.ReleatedPlanningProject = val[0].oid
    },
    reduceHiddenField(arr,removeArray) {
      let finalArray = [] 
      arr.forEach(item => {
        if(removeArray.indexOf(item) == -1) {
          finalArray.push(item)
        }
      })
      return finalArray
    },
    // 提交项目
    submitProject() {
      if(this.requireObj.ProjectBudget && Number(this.requireObj.ProjectBudget) !== Number(this.requireObj.ProjectBudget)) {
        Message.error('项目预算类型只能为数值')
        return false
      }
      if(this.requireObj.ProjectBonus && Number(this.requireObj.ProjectBonus) !== Number(this.requireObj.ProjectBonus)){
        Message.error('项目奖金类型只能为数值')
        return false
      }
      // if (this.requireObj.ProjectBudget) {
      //   this.requireObj.ProjectBudget = Number(this.requireObj.ProjectBudget)
      // }
      // console.log(this.requireObj, 485);
      this.beforeSubmit = true
      let checkedItem = JSON.parse(JSON.stringify(this.checkedItem))
      if(this.projectTypeData && this.projectTypeData[0] && this.projectTypeData[0].name === "cn.com.sany.ProcessImprovementProject" && this.requireObj.ProjectSmallType ) {
        if(this.requireObj.ProjectSmallType.indexOf("新工艺技术项目") != -1) {
          checkedItem =  this.reduceHiddenField(this.checkedItem,["RequirementsSource","TechnologySpecialty","IslightPlant"])
        } else if(this.requireObj.ProjectSmallType.indexOf("技改") != -1) {
          checkedItem = this.reduceHiddenField(this.checkedItem,["ImportantGrade","RequirementsSource","ProjectBonus"])
        } else {
          checkedItem = this.reduceHiddenField(this.checkedItem,["ImportantGrade","ProjectBonus","TechnologySpecialty","isEquipmentModification"])
        }
      } 
      checkedItem.some(item => {
        if(!this.requireObj[item]){
          Message.error('带*的为必填项')
          this.checked = false
          return true
        }else {
          this.checked = true
        }
      })
      if(this.checked){
        if(this.isSubmit){
          return false
        }
        let isModification = null
        // console.log(this.requireObj.isEquipmentModification,checkedItem);
        if(this.requireObj.isEquipmentModification === "是") {
          if(this.requireObj.ProjectSmallType && this.requireObj.ProjectSmallType.indexOf("技改") != -1) {
            isModification =  false
          } else {
            Message.error("涉及设备改造项目的项目，请选择技改项目（新工艺技术）项目小类！")
            isModification = true
          }
        }
        if(isModification) return
        if(this.projectTypeData && this.projectTypeData[0] && this.projectTypeData[0].name === "cn.com.sany.ProcessImprovementProject" && this.requireObj.ProjectSmallType ) {
        if(this.requireObj.ProjectSmallType.indexOf("新工艺技术项目") != -1) {
          this.$set(this.requireObj,"RequirementsSource","")
          this.$set(this.requireObj,"TechnologySpecialty","")
        } else if(this.requireObj.ProjectSmallType.indexOf("技改") != -1) {
          this.$set(this.requireObj,"ImportantGrade","")
          this.$set(this.requireObj,"RequirementsSource","")
          this.$set(this.requireObj,"ProjectBonus","")
        } else {
          this.$set(this.requireObj,"ImportantGrade","")
          this.$set(this.requireObj,"ProjectBonus","")
          this.$set(this.requireObj,"TechnologySpecialty","")
          this.$set(this.requireObj,"isEquipmentModification","")
        }
      }
        this.isSubmit = true
        this.spinning = true
        setTimeout(()=>{
          this.isSubmit = false
        }, 3000)
        let params = {
          userId: this.userId,
          values: this.requireObj,
          type: this.objType,
          oid: `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem("oid")}`,
        }
        saveProject(params).then(res => {
          if(res.status === 200) {
            if(res.data && res.data.success) {
              this.spinning = false
              Message.success("项目提交成功")
              this.routerPage()
            }else{
              this.spinning = false
              Message.error(res.data.message)
            }
          }else{
            this.spinning = false
            Message.error("项目提交失败")
          }
        })
      }
    },
    // 取消项目
    cancelProject(){
      this.routerPage()
    },
    routerPage() {
      let tabArr = JSON.parse(sessionStorage.getItem('tabArr'))
      let newTabArr = tabArr.filter(iv => {
        return iv.path !== '/single/projectMain/editProject'
      })
      this.$store.commit("SET_TABS", newTabArr); // 赋值
      this.$router.push({
        path: '/single/projectMain',
        query: {
          oid: sessionStorage.getItem("oid")
        }
      })
    },
    // 选出需要校验的项
    checkProject() {
      let arr = []
      this.fromData[0].rows.forEach(item =>{
        item.items.forEach(i =>{
          if(i.required){
            arr.push(i.id)
          }
        })
      })
      let projectIdx = arr.findIndex(item => item === "projectShortName"),mangerIdx = arr.findIndex(item => item === "ProjectMananger")
      if(projectIdx != -1) {
        arr.splice(projectIdx, 1)
      }
      if(!this.requireObj.ProjectMananger && mangerIdx != -1){
        arr.splice(mangerIdx, 1)
      }
      this.checkedItem = arr
    }
  }
};
</script>
<style lang="less" scoped>
.editProject {
  padding: 20px;
  position: relative;
  background-color: #fff;
  // height: calc(100vh - 213px);
  min-height: 73vh;
  padding: 20px;
  .projectConetnt {
    // padding: 10px 20px;
    .createTitle {
      font-size: 18px;
      color: #333;
      // margin-bottom: 10px;
      font-weight: 550;
      margin-bottom: 16px;
    }
    .createProper .fromBox .modalTitle {
      display: none;
    }
  }
  /deep/ .ant-spin-container{
     min-height: 73vh;
  }
  .footer {
    // position: relative;
    // bottom: 0px;
    margin-top: 50px;
    display: flex;
    justify-content: flex-end;
    width: 100%;
    height: 56px;
    border: none;
    border-radius: 1px;
    border: none;
    box-shadow: 2px 0px 4px #ccc;
    padding: 12px;
    .cancel {
      padding: 7px 20px;
      border: 1px solid #ccc;
      border-radius: 4px;
      text-align: center;
      line-height: 18px;
      cursor: pointer;
    }
    .confirm {
      margin-left: 15px;
      padding: 7px 20px;
      background-color: #386bd7;
      border-radius: 4px;
      text-align: center;
      line-height: 18px;
      color: #fff;
      cursor: pointer;
    }
  }
}
</style>